/*
 * Copyright 2023-2085 xujin <ceo@itgrail.com>
 *
 * Licensed under the Grail License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://itgrail.com/docs?id=3&catalogId=87
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.itgrail.pilot.app.command.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Preconditions;
import com.itgrail.pilot.app.command.cmo.query.DetailAlignUserCmd;
import com.itgrail.pilot.app.command.co.*;
import com.itgrail.pilot.app.converter.KeyResultClientConverter;
import com.itgrail.pilot.app.converter.ObjectiveClientConverter;
import com.itgrail.pilot.app.converter.OkrPeriodClientConverter;
import com.itgrail.pilot.domain.user.contant.OkrConstants;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.*;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import com.itgrail.grail.cqrs.annotation.CmdHandler;
import com.itgrail.grail.cqrs.command.CommandExecutorI;
import com.itgrail.grail.dto.ResultData;
import com.itgrail.grail.exception.BusinessException;
import com.itgrail.grail.utils.reflect.BeanMapper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


@CmdHandler
public class DetailAlignUserCmdExe implements CommandExecutorI<ResultData, DetailAlignUserCmd> {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OkrPeriodMapper okrPeriodMapper;

    @Autowired
    private ObjectiveMapper mapper;

    @Autowired
    private KeyResultMapper keyResultMapper;

    @Autowired
    private ObjectiveClientConverter objectiveClientConverter;

    @Autowired
    private KeyResultClientConverter keyResultClientConverter;

    @Autowired
    private OkrPeriodClientConverter okrPeriodClientConverter;

    @Autowired
    private ClassifyMapper classifyMapper;

    @Autowired
    private UserOkrAlignMapper userOkrAlignMapper;


    @Override
    public ResultData execute(DetailAlignUserCmd cmd) {
        ResultData resultData = ResultData.success(null);
        check(cmd);
        List<UserCO> usersInfo = getUsersInfo(cmd);
        //查询出当前O关联的O
        List<Integer> alignObjectivesById = getAlignObjectivesById(cmd);
        List<AlignUserCO> alignUserCOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(usersInfo)) {
            usersInfo.forEach(x -> {
                AlignUserCO alignUserCO = BeanMapper.map(x, AlignUserCO.class);
                List<OkrDetailCO> objectiveDetailCOS = new ArrayList<>();
                List<Integer> userOkrs = findUserOkrs(x.getUserId(), cmd.getPeriodId());
                if (!CollectionUtils.isEmpty(userOkrs)) {
                    userOkrs.forEach(objectiveId -> {
                        OkrDetailCO detail = findDetail(objectiveId);
                        if (!CollectionUtils.isEmpty(alignObjectivesById) && alignObjectivesById.contains(objectiveId)) {
                            detail.setAlign(true);
                        }
                        objectiveDetailCOS.add(detail);
                    });
                }
                alignUserCO.setObjectiveDetailCOS(objectiveDetailCOS);
                alignUserCOS.add(alignUserCO);
            });
        }
        resultData.setData(alignUserCOS);
        return resultData;
    }

    protected boolean check(DetailAlignUserCmd cmd) {
        Preconditions.checkNotNull(cmd, "cmd不能为null");
        Preconditions.checkNotNull(cmd.getKey(), "参数不能为空");
        return true;
    }

    protected List<UserCO> getUsersInfo(DetailAlignUserCmd cmd) {
        List<UserCO> list = new ArrayList<>();
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", OkrConstants.NOT_DELETED);
        queryWrapper.and(qw -> qw.like("name", cmd.getKey()).or().eq("person_code", cmd.getKey()));
        if (cmd.getCurrentUserId() != null) {
            queryWrapper.notIn("user_id", cmd.getCurrentUserId());
        }
        List<UserDO> userDOS = userMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(userDOS)) {
            userDOS.forEach(x -> {
                UserCO userCO = BeanMapper.map(x, UserCO.class);
                list.add(userCO);
            });
        }
        return list;
    }

    protected List<Integer> getAlignObjectivesById(DetailAlignUserCmd cmd) {
        List<Integer> list = new ArrayList<>();
        QueryWrapper<UserOkrAlignDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", OkrConstants.NOT_DELETED);
        queryWrapper.eq("okr_period", cmd.getPeriodId());
        queryWrapper.eq("start_objective_id", cmd.getStartObjectiveId());
        List<UserOkrAlignDO> alignDOList = userOkrAlignMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(alignDOList)) {
            list = alignDOList.stream().map(UserOkrAlignDO::getAcceptObjectiveId).collect(Collectors.toList());
        }
        return list;
    }

    /**
     * 封装okr详情
     *
     * @param objectiveId
     * @return
     */
    protected OkrDetailCO findDetail(Integer objectiveId) {
        OkrDetailCO okrDetailCO = new OkrDetailCO();
        //获取目标信息
        ObjectiveDO objectiveDO = mapper.selectById(objectiveId);

        ObjectiveDetailCO objectiveDetailCO = objectiveClientConverter.dataToClient(objectiveDO);
        Integer classifyId = objectiveDO.getClassifyId();
        ClassifyDO classifyDO = classifyMapper.selectById(classifyId);
        if (null != classifyDO) {
            objectiveDetailCO.setClassifyName(classifyDO.getName());
        }
        okrDetailCO.setObjectiveDetailCO(objectiveDetailCO);
        if (objectiveDO == null) {
            throw new BusinessException("500", "没有查询到OKR内容");
        }
        //获取考核周期实体
        OkrPeriodDO okrPeriodDO = okrPeriodMapper.selectById(objectiveDO.getOkrPeriodId());
        OkrPeriodDetailCO okrPeriodDetailCO = okrPeriodClientConverter.dataToClient(okrPeriodDO);
        okrDetailCO.setOkrPeriodDetailCO(okrPeriodDetailCO);

        //获取关键成果
        QueryWrapper<KeyResultDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", OkrConstants.NOT_DELETED);
        queryWrapper.eq("objective_id", objectiveId);
        List<KeyResultDO> keyResultDOS = keyResultMapper.selectList(queryWrapper);
        List<KeyResultDetailCO> keyResultDetailCOS = keyResultClientConverter.dataToClients(keyResultDOS);
        okrDetailCO.setKeyResultDetailCO(keyResultDetailCOS);
        return okrDetailCO;
    }

    /**
     * 查询用户当前周期下的所有okr
     *
     * @return
     */
    protected List<Integer> findUserOkrs(Integer userId, Integer periodId) {
        QueryWrapper<ObjectiveDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", OkrConstants.NOT_DELETED);
        queryWrapper.eq("created", userId);
        queryWrapper.eq("okr_period_id", periodId);
        List<ObjectiveDO> objectiveDOS = mapper.selectList(queryWrapper);
        return Optional.ofNullable(objectiveDOS).orElse(Arrays.asList())
                .stream()
                .map(ObjectiveDO::getId)
                .collect(Collectors.toList());
    }

}
